/*
 * Created on Jan 30, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package org.scohen.juploadr.app;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.scohen.juploadr.Messages;
import org.scohen.juploadr.app.tags.Tag;
import org.scohen.juploadr.app.tags.TagPainter;
import org.scohen.juploadr.app.tags.TagParser;
import org.scohen.juploadr.ui.MultiSelectThumbnail;
import org.scohen.juploadr.ui.ReusableUIFactory;
import org.scohen.juploadr.uploadapi.ImageUploadApi;
import org.scohen.juploadr.uploadapi.abilities.Abilities;
import org.scohen.juploadr.uploadapi.abilities.PhotoAbilities;
import org.scohen.juploadr.util.TextUtils;

/**
 * @author steve
 * 
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class MultiImageAttributesUI extends ImageAttributesUI {
    private List<ImageAttributes> thumbnails;
    private MultiSelectThumbnail th;
    private TagPainter painter;
    private Set<Tag> allTagsAtStart;
    private String originalDescription;

    public MultiImageAttributesUI(List<ImageAttributes> atts) {
        super(((ImageAttributes) atts.get(0)));
        originalDescription = getNonNullString(atts.get(0).getDescription());
        thumbnails = atts;
        allTagsAtStart = new LinkedHashSet<Tag>();
        for (ImageAttributes a : thumbnails) {
            allTagsAtStart.addAll(a.getTags());
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.scohen.juploadr.app.ImageAttributesUI#getThumbnailCanvas(org.eclipse.swt.widgets.Composite)
     */
    protected void addThumbnails(Composite thumbnailComposite) {
        window
                .setText(Messages.getString("juploadr.ui.multiimageattributes.dialog.title") + thumbnails.size() + Messages.getString("juploadr.ui.multiimageattributes.dialog.title.suffix")); //$NON-NLS-1$ //$NON-NLS-2$

        GridLayout layout = new GridLayout();
        layout.numColumns = 1;
        layout.verticalSpacing = 1;
        thumbnailComposite.setLayout(layout);

        th = new MultiSelectThumbnail(thumbnailComposite, thumbnails);

        thumbnailComposite.setSize(SWT.DEFAULT, SWT.DEFAULT);
    }

    protected void gatherData() {

        String title = txtTitle.getText();
        String description = txtDescription.getText();
        String tags = txtTags.getText();
        boolean isPublic = radioPublic.getSelection();
        boolean isPrivate = radioPrivate.getSelection();
        boolean family = checkFamily.getSelection();
        boolean friends = checkFriends.getSelection();
        
        for(ImageAttributes attrs : thumbnails){
            if (TextUtils.notEmpty(title)) {
                attrs.setTitle(title);
            }
            if (TextUtils.notEmpty(description) && !originalDescription.equalsIgnoreCase(description)) {
                StringBuffer sb = new StringBuffer(getNonNullString(attrs.getDescription()));
                sb.append(" ");
                sb.append(getNonNullString(description));
                attrs.setDescription(sb.toString().trim());
            }
            if (TextUtils.notEmpty(tags)) {
                Set<Tag> oldTags = new LinkedHashSet<Tag>();
                oldTags.addAll(attrs.getTags());
                for (ImageAttributes a : thumbnails) {
                    oldTags.addAll(a.getTags());
                }

                Set<Tag> newTags = TagParser.parse(tags);
                Set<Tag> tagsToAdd = new LinkedHashSet<Tag>();
                for (Tag tag : newTags) {
                    if (!oldTags.contains(tag) || painter.tagAppliesToAll(tag)) {
                        tagsToAdd.add(tag);
                    }
                }

                Set<Tag> tagsToDelete = new HashSet<Tag>();
                for (Tag tag : allTagsAtStart) {
                    if (!newTags.contains(tag)) {
                        tagsToDelete.add(tag);
                    }
                }
                
                for (ImageAttributes a : thumbnails) {
                    a.getTags().addAll(tagsToAdd);
                    a.getTags().removeAll(tagsToDelete);
                }

            } else {
                // no tags means we sholdn't have any tags in the attributes either.
                attrs.getTags().clear();
            }
            if (isPublic) {
                attrs.setPubliclyVisible(true);
            } else if (isPrivate) {
                attrs.setPubliclyVisible(false);
                attrs.setFamilyViewable(family);
                attrs.setFriendViewable(friends);
            }
            attrs.getButton().redraw();
            if ( ImageUploadApi.getInstance().getAbilities().getGeoAbilities().hasGeoAbilities()) {
                attrs.setLocation(geoTab.getGeoLocation());
            }
        }

    }

    protected void addPhotosToPhotoset(PhotoSet set) {
        super.addPhotosToPhotoset(set);
        for(ImageAttributes atts : thumbnails){
            set.addPhoto(atts);
        }
    }
    
    protected void removePhotosFromPhotoset(PhotoSet set) {
        super.removePhotosFromPhotoset(set);
        for(ImageAttributes photo : thumbnails){
            set.removePhoto(photo);
        }
    }

    @Override
    protected boolean appliesToAll(PhotoSet p) {
        for (ImageAttributes atts : thumbnails) {
            if (!atts.getPhotoSets().contains(p)) {
                return false;
            }
        }
        return true;
    }

    @Override
    protected boolean appliesToNone(PhotoSet p) {
        return !appliesToAll(p);
    }

    @Override
    protected void addNavigationButtons(Composite bc) {
        // no nav buttons here.
    }

    protected void initDefaultValues(PhotoAbilities abilities) {

        UploadImage initial = (UploadImage) thumbnails.get(0);

        radioPrivate.setSelection(!initial.isPubliclyVisible());
        radioPublic.setSelection(initial.isPubliclyVisible());
        checkFamily.setSelection(initial.isFamilyViewable());
        checkFriends.setSelection(initial.isFriendViewable());
        txtDescription.setText(getNonNullString(initial.getDescription()));
        txtTitle.setText(getNonNullString(initial.getTitle()));
        boolean shouldCheckFriends = initial.isFriendViewable();
        boolean shouldCheckFamily = initial.isFamilyViewable();
        boolean shouldCheckPrivacy = true;
        if (ImageUploadApi.getInstance().getAbilities().getPhotoAbilities().hasTags()) {
            painter = new TagPainter(txtTags, thumbnails);
            txtTags.getContent().addTextChangeListener(painter);
            Set<Tag> allTags = new LinkedHashSet<Tag>();
            for (ImageAttributes atts : thumbnails) {
                allTags.addAll(atts.getTags());
            }
            StringBuffer sb = new StringBuffer();
            for (Tag t : allTags) {
                sb.append(t.toString());
                sb.append(" ");
            }
            txtTags.setText(sb.toString().trim());
            txtTags.addMouseListener(painter);
        }
        
        for(UploadImage attrs : thumbnails) {
            
            if (!originalDescription.equals(getNonNullString(attrs.getDescription()))) {
                txtDescription.setText(""); //$NON-NLS-1$
            }

            if (!txtTitle.getText().equals(getNonNullString(attrs.getTitle()))) {
                txtTitle.setText(""); //$NON-NLS-1$
            }

            if (shouldCheckPrivacy && radioPublic.getSelection() != attrs.isPubliclyVisible()) {
                radioPublic.setSelection(false);
                radioPrivate.setSelection(false);
                checkFamily.setEnabled(false);
                checkFriends.setEnabled(false);
                shouldCheckPrivacy = false;
            }
            if (shouldCheckFriends && checkFriends.getSelection() != attrs.isFriendViewable()) {
                checkFriends.setSelection(false);
                shouldCheckFriends = false;
            }
            if (shouldCheckFamily && checkFamily.getSelection() != attrs.isFamilyViewable()) {
                checkFamily.setSelection(false);
                shouldCheckFamily = false;
            }
        }

        if (radioPublic.getSelection()) {
            checkFamily.setEnabled(false);
            checkFriends.setEnabled(false);
        }

    }

    private String getNonNullString(String str) {
        if (str == null) {
            return ""; //$NON-NLS-1$
        }
        return str;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.scohen.juploadr.app.ImageAttributesUI#rotateClicked(org.eclipse.swt.events.MouseEvent)
     */
    protected void rotateClicked(SelectionEvent event) {
        int rotation = 0;
        if (event.widget == rotateLeft) {
            rotation = 360 - 90;
        } else {
            rotation = 90;
        }
        for (int i = 0; i < thumbnails.size(); i++) {
            ImageAttributes thumb = (ImageAttributes) thumbnails.get(i);
            thumb.setRotation((thumb.getRotation() + rotation) % 360);
        }
        thumbnailComposite.redraw();
        th.redraw();
    }

    public static void main(String[] args) {
        JUploadr uploadr = new JUploadr();
        File pearPath = new File(args[0]);
        ImageAttributes atts = new ImageAttributes(uploadr, uploadr.images, pearPath.getAbsolutePath());
        List<ImageAttributes> images = new ArrayList<ImageAttributes>();
        images.add(atts);
        MultiImageAttributesUI ui = new MultiImageAttributesUI(images);
        ui.show(ReusableUIFactory.getInstance().getDisplay());

    }
}